/** @format */

import { ref } from 'vue';
import { defineStore } from 'pinia';
import Dialog401 from '@/components/dialog-401/index';
import router from '@/router';
const { currentRoute, replace } = router;

// 用户信息存储的key
const TOKEN_KEY = 'USER_TOKEN';
const USER_INFO_KEY = 'USER_INFO';
const USER_DATA_KEY = 'USER_DATA';

export const useUserStore = defineStore('user', () => {
  // 用户token
  const token = ref<string>(localStorage.getItem(TOKEN_KEY) || '');
  // 用户信息
  const userInfo = ref<any>(
    JSON.parse(localStorage.getItem(USER_INFO_KEY) || '{}'),
  );
  // 用户数据
  const userData = ref<any>(
    JSON.parse(localStorage.getItem(USER_DATA_KEY) || '{}'),
  );
  // 登录状态
  const isLogin = ref<boolean>(!!token.value);

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken;
    localStorage.setItem(TOKEN_KEY, newToken);
    isLogin.value = true;
  };
  // 获取token
  const getToken = () => {
    return token.value;
  };
  // 判断是否登录
  const onJudgeLogin = (collback: Function) => {
    if (!token.value) {
      Dialog401({
        onConfirm: () => {
          localStorage.removeItem('token');
          if (currentRoute.value.path != '/login') {
            replace('/login?redirect=' + currentRoute.value.fullPath);
          }
        },
        onCancel: () => {
          console.log('用户点击了取消按钮');
        },
      });
    } else {
      collback();
    }
  };

  // 设置用户信息
  const setUserInfo = (info: any) => {
    userInfo.value = info;
    localStorage.setItem(USER_INFO_KEY, JSON.stringify(info));
  };

  // 获取用户信息
  const getUserInfo = () => {
    return userInfo.value;
  };

  // 清除用户信息
  const clearUserInfo = () => {
    token.value = '';
    userInfo.value = {};
    isLogin.value = false;
    localStorage.removeItem(TOKEN_KEY);
    localStorage.removeItem(USER_INFO_KEY);
    localStorage.removeItem(USER_DATA_KEY);
    userData.value = {};
  };

  // 设置用户数据
  const setUserData = (data: any) => {
    userData.value = data;
    localStorage.setItem(USER_DATA_KEY, JSON.stringify(data));
  };
  // 获取用户数据
  const getUserData = () => {
    return userData.value;
  };

  return {
    token,
    setToken,
    getToken,

    userInfo,
    setUserInfo,
    getUserInfo,
    clearUserInfo,

    isLogin,
    onJudgeLogin,

    userData,
    setUserData,
    getUserData,
  };
});
